#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>

const int num = 5;

pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;

void* Wait(void* agrs)
{
    const char* name = static_cast<const char*>(agrs);
    while(1)
    {
        pthread_mutex_lock(&gmutex);
        pthread_cond_wait(&gcond, &gmutex);
        usleep(10000);

        std::cout << name << " is running" << std::endl;
        pthread_mutex_unlock(&gmutex);
    }

    return nullptr;
}

int main()
{
    pthread_t threads[num];
    for(int i = 0 ; i < num; i++)
    {
        char* name = new char[64];
        snprintf(name, 64, "thread-%d", i+1);
        pthread_create(threads+i, nullptr, Wait, (void*)name);
    }

    // 唤醒其他线程
    while(1)
    {
        // pthread_cond_signal(&gcond);
        pthread_cond_broadcast(&gcond);
        std::cout << "唤醒一个线程...." << std::endl;
        sleep(2);
    }

    for(int i = 0; i < num; i++)
    {
        pthread_join(threads[i], nullptr);
    }

    return 0;
}